package com.hongxun.design.alipay;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.hongxun.design.MyApp;
import com.hongxun.design.bean.PayBackBean;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.object_properties.MyMessage;
import com.hongxun.design.utils.fastjson.FastJsonUtil;

/**
 * Created by zerdoor_pc on 2015/11/3.
 */
public class AlipayUser extends FragmentActivity {
    private static final int ADD_GOODS = 3;

    String callback = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastShow.showShort(AlipayUser.this, "支付成功");
                        MyLog.L(MString.SUCCESSED + "支付成功");
                        returnBack();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastShow.showShort(AlipayUser.this, "支付结果确认中");
                            MyLog.L(MString.SUCCESSED + "支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastShow.showShort(AlipayUser.this, "支付失败");
                            MyLog.L(MString.SUCCESSED + "支付失败");
                            returnBack();
                        }
                    }
                    break;
                }


                case SDK_CHECK_FLAG:
                    String sign= (String) msg.obj;
                    if (sign.length() != 0) {
                        pay(sign);
                    } else {
                        ToastShow.showShort(AlipayUser.this, "交易出错，请重新开始！");
                        returnBack();
                    }
                    break;
                case ADD_GOODS:


                    PayBackBean bean = FastJsonUtil.getPayBackBean((String) msg.obj);
                    if (bean.getCode()!=null&&bean.getCode().equals(MString.SUCCESS)) {
                        mHandler.sendMessage(MyMessage.getMessage(SDK_CHECK_FLAG,bean.getData()));
                        //getSDKVersion();
                    } else {
                        ToastShow.showShort(AlipayUser.this, bean.getCode());
                        returnBack();
                    }


                    //  RootCodeTwo root = JsonParser.CheckCodeTwo((String) msg.obj);
                    // if ((root.type != null) ? (root.type.equals(MyString.PAYMENT)): (root.type != null)) {
                    //      sign = root.msg;
                    //      check();
                    //  } else {
                    //   if ("SUCCESS".equals(root.code)) {
                    //        AddNewWebView.Refresh(ShardPreferencesTool.getshare(AlipayUser.this, MyString.CALLBACK, MyString.NULL), MyString.SUCCESS);
                    //       ShardPreferencesTool.saveshare(AlipayUser.this, MyString.CALLBACK, MyString.NULL);
                    //  } else {
                    //      AddNewWebView.Refresh(ShardPreferencesTool.getshare(AlipayUser.this, MyString.CALLBACK, MyString.NULL), MyString.FILED);
                    //       ShardPreferencesTool.saveshare(AlipayUser.this, MyString.CALLBACK, MyString.NULL);
                    //  }
                    //    returnBack();
                    // }
                    break;

                default:
                    break;
            }
        }

    };

    //private String sign = "";

    private void returnBack() {
        this.finish();
    }

    String payid = "", buy_menu_id = "", people_num = "", type = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bun = getIntent().getExtras();
        payid = bun.getString("payid");
        buy_menu_id = bun.getString("buy_menu_id");
        people_num = bun.getString("people_num");
        type = bun.getString("type");
        MyLog.L(MString.SUCCESSED + "33== payid=" + payid + "&buy_menu_id=" + buy_menu_id + "&people_num=" + people_num + "&type=" + type);
        sendHttpGetGoods();

    }

    /**
     * 获取支付码*
     */
    private void sendHttpGetGoods() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MyApp.HTTP.payment(mHandler, ADD_GOODS, payid, buy_menu_id, people_num, type);
                // MyHttp.PAYCONTROL(mHandler, ADD_GOODS, ShardPreferencesTool.getshare(AlipayUser.this, "openId", ""), order, paytype, channel, score, money);
            }
        }).start();
    }

    private void pay(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AlipayUser.this);
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    /**
     * get the sdk version. 获取SDK版本号
     *
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        ToastShow.showShort(this, version);
    }

}
